package com.navi.core.controller;

import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static com.navi.core.constant.GenericDef.JAVASCRIPT_ERROR_LOG;

@RestController
public class ToolController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String CLIENT_INFO_LOG = "Client-report";
    private static final String CLIENT_INFO_TYPE_CLIENT_REPORT = "R";
    private static final String CLIENT_INFO_TYPE_ERROR_REPORT = "E";

    @RequestMapping(value = "/client", method = RequestMethod.POST)
    public String clientReport(HttpServletRequest request,
                               HttpServletResponse response,
                               @RequestParam(value = "type", required = false) String type,
                               @RequestParam(value = "msg", required = false) String msg,
                               @RequestParam(value = "ext", required = false) String ext) {
        //获取浏览器信息
        Browser browser = UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getBrowser();
        //获取浏览器版本号
        Version version = browser.getVersion(request.getHeader("User-Agent"));

        // IP & Hostname
        String clientIP = request.getHeader("X-FORWARDED-FOR");
        if (StringUtils.isEmpty(clientIP)) {
            clientIP = request.getRemoteAddr();
        }
        String clintHost = request.getRemoteHost();

        // User info
        HttpSession session = request.getSession();
        String userID = (String) session.getAttribute("userId");

        String tmp = String.format("[user: %s - %s - %s] [browser: %s - %s]",
                userID, clientIP, clintHost,
                browser, version);

        if (CLIENT_INFO_TYPE_ERROR_REPORT.equals(type)) {
            logger.error("{} {}: Error msg:{}. {}",
                    JAVASCRIPT_ERROR_LOG, tmp, msg, ext);
        } else {
            logger.info("{} {}: {}",
                    CLIENT_INFO_LOG,
                    tmp,
                    msg);
        }

        return "OK";
    }
}
